package com.ruoyi.match.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import com.ruoyi.match.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeDriverService;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.remote.CapabilityType;

import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author sjz
 * @version 1.0.0
 * @desc
 * @date 2023/11/3 20:00
 **/

@Slf4j
public class BrowserUtil {

    public static WebDriver createBrowser() throws IOException {

        ChromeOptions chromeOptions = new ChromeOptions();
        //删除提示栏
        chromeOptions.addArguments("disable-infobars");

        // 设置后台静默模式启动浏览器
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--disable-dev-shm-usage");
//        chromeOptions.addArguments("--debuggerAddress","127.0.0.1:9527");

        Map<String, Object> prefs = new HashMap<String, Object>();
        //禁止弹出通知
        prefs.put("profile.default_content_setting_values.notifications", 2);

        //禁止加载图片
        prefs.put("profile.managed_default_content_settings.images", 2);

        //禁止加载css
        prefs.put("permissions.default.stylesheet", 2);

        chromeOptions.setExperimentalOption("prefs", prefs);

        // 关闭界面上的---Chrome正在受到自动软件的控制
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        //无痕模式
        chromeOptions.addArguments("--incognito");
//        chromeOptions.addArguments("--user-data-dir=C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data");
        chromeOptions.addArguments("--remote-allow-origins=*");
//        Connection connect = Jsoup.connect("http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=11&pack=284616&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=2&regions=&gm=4");
        Connection connect = Jsoup.connect("http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4");
        try {
            String text = connect.get().body().text();
            if(StrUtil.isNotBlank(text)){
                log.info("代理IP:"+text);
                Proxy proxy = new Proxy();
                proxy.setHttpProxy(text);
                proxy.setSslProxy(text);
                chromeOptions.setCapability(CapabilityType.PROXY,proxy);
//                chromeOptions.setProxy(proxy);
//                chromeOptions.setCapability("proxy", proxy);
//                chromeOptions.addArguments("--proxy-server="+text);
            }
        }catch (Exception e){
            log.error("使用代理发生异常");
            connect =  Jsoup.connect("http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4");
            String text = connect.get().body().text();
            if(StrUtil.isNotBlank(text)){
                log.info("代理IP:"+text);
//                chromeOptions.addArguments("--proxy-server="+text);
                Proxy proxy = new Proxy();
                proxy.setHttpProxy(text);
                proxy.setSslProxy(text);
                chromeOptions.setCapability(CapabilityType.PROXY,proxy);
//                chromeOptions.setCapability("proxy", proxy);
            }
        }

        ChromeDriverService driverService;
        OsInfo osInfo = SystemUtil.getOsInfo();
        String name = osInfo.getName();
        if(!name.toLowerCase().contains("windows")) {
            chromeOptions.addArguments("user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
            chromeOptions.addArguments("--no-sandbox"); // 为了让root用户也能执行
            driverService =new ChromeDriverService.Builder().usingDriverExecutable(new File(CommonConstants.DRIVER_PATH_PROD)).usingAnyFreePort().build();
        }else {
            //设置header，以user-agent为例
            chromeOptions.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36");
            driverService = new ChromeDriverService.Builder().usingDriverExecutable(new File(CommonConstants.DRIVER_PATH_DEV)).usingAnyFreePort().build();
        }




        ChromeDriver chromeDriver = new ChromeDriver(driverService,chromeOptions);
        //全屏
        chromeDriver.manage().window().maximize();
        //删除所有cookie
//        chromeDriver.manage().deleteAllCookies();
        //设置全局等待时间：等待10秒如果某元素还未出现，操作时该元素会报错
        chromeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        return chromeDriver;
    }


    public static boolean isExistElement(WebElement webElement, By by) {
        try {
            webElement.findElement(by);
            //可以把上边一行，换成下边注释掉的这一行，指定时间在dom树中没找到这个元素就报错
            //new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.id("")));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static WebDriver createBrowser2() throws IOException {
        ChromeOptions chromeOptions = new ChromeOptions();
//        chromeOptions.addArguments("--debuggerAddress","127.0.0.1:9527");
        //删除提示栏
        chromeOptions.addArguments("disable-infobars");
        // 设置后台静默模式启动浏览器
//        chromeOptions.addArguments("--headless");

        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--disable-dev-shm-usage");
        chromeOptions.addArguments("--blink-settings=imagesEnabled=false");


        // 关闭界面上的---Chrome正在受到自动软件的控制
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        //无痕模式
        chromeOptions.addArguments("--incognito");

        chromeOptions.addArguments("--remote-allow-origins=*");

        chromeOptions.addArguments("--user-data-dir=C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data");
//        Connection connect = Jsoup.connect("http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=11&pack=284616&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=2&regions=&gm=4");
        Connection connect = Jsoup.connect("http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4");
        try {
            String text = connect.get().body().text();
            if(StrUtil.isNotBlank(text)){
                log.info("代理IP:"+text);
                Proxy proxy = new Proxy();
                proxy.setHttpProxy(text);
                proxy.setSslProxy(text);
                chromeOptions.setCapability(CapabilityType.PROXY,proxy);
//                chromeOptions.setProxy(proxy);
//                chromeOptions.setCapability("proxy", proxy);
//                chromeOptions.addArguments("--proxy-server="+text);
            }
        }catch (Exception e){
            log.error("使用代理发生异常");
            connect =  Jsoup.connect("http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4");
            String text = connect.get().body().text();
            if(StrUtil.isNotBlank(text)){
                log.info("代理IP:"+text);
//                chromeOptions.addArguments("--proxy-server="+text);
                Proxy proxy = new Proxy();
                proxy.setHttpProxy(text);
                proxy.setSslProxy(text);
                chromeOptions.setCapability(CapabilityType.PROXY,proxy);
//                chromeOptions.setCapability("proxy", proxy);
            }
        }

        ChromeDriverService driverService;
        OsInfo osInfo = SystemUtil.getOsInfo();
        String name = osInfo.getName();
        if(!name.toLowerCase().contains("windows")) {
            chromeOptions.addArguments("user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36");
            chromeOptions.addArguments("--no-sandbox"); // 为了让root用户也能执行
            driverService =new ChromeDriverService.Builder().usingDriverExecutable(new File(CommonConstants.DRIVER_PATH_PROD)).usingAnyFreePort().build();
        }else {
            //设置header，以user-agent为例
            chromeOptions.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36");
            driverService = new ChromeDriverService.Builder().usingDriverExecutable(new File(CommonConstants.DRIVER_PATH_DEV)).usingAnyFreePort().build();
        }




        ChromeDriver chromeDriver = new ChromeDriver(driverService,chromeOptions);
        //全屏
        chromeDriver.manage().window().maximize();
        //删除所有cookie
        chromeDriver.manage().deleteAllCookies();
        //设置全局等待时间：等待10秒如果某元素还未出现，操作时该元素会报错
        chromeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        return chromeDriver;
    }
}
